package com.jianglin.controller;


import com.jianglin.model.Userinfo;
import com.jianglin.service.IUserinfoService;
import com.jianglin.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
 *
 *
 * @author liyijia
 */

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private IUserinfoService userinfoService;


    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Map<String, Object> loginIn(@RequestBody Userinfo userinfo) {
        Map<String, Object> map = new HashMap<>(100);

        try {
            // 先检查用户是否存在
            Userinfo user = userinfoService.findUserByName(userinfo.getUsername());
            if (user == null) {
                map.put("code", 404);
                map.put("msg", "用户不存在");
                // 直接返回，不需要进行认证
                return map;
            }

            // 用户存在则进行认证
            authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(userinfo.getUsername(), userinfo.getPassword())
            );

            // 认证成功后生成token
            String token = jwtUtil.generateToken(userinfo.getUsername());
            System.out.println(token);

            map.put("code", 0);
            map.put("user", user);
            map.put("username", user.getUsername());
            map.put("token", token);

        } catch (BadCredentialsException e) {
            // 密码错误情况
            map.put("code", 401);
            map.put("msg", "密码错误");
        } catch (Exception e) {
            // 其他异常
            map.put("code", 500);
            map.put("msg", "系统错误: " + e.getMessage());
        }
        return map;
    }


}
